import os
import simplejson as enc
import gettext

import logging
root_path = os.path.join(os.path.dirname(__file__), '')
print root_path

def gettext_json(domain, path, langs = [], indent = False):
    try:
        tr = gettext.translation(domain, path, langs)
        # for unknown reasons, instead of having plural entries like 
        # key: [sg, pl1...]
        # tr._catalog has (key, n): pln, 
        keys = tr._catalog.keys()
        keys.sort()
        ret = {}
        for k in keys:
            if not k: continue
            v = tr._catalog[k]
            if type(k) is tuple:
                if k[0] not in ret:
                    ret[k[0]] = []
                ret[k[0]].append(v)
            else:
                ret[k] = v
#        return enc.dumps(ret, ensure_ascii = False, indent = indent)
        print ret
        print ret['<add new post>']
        dump = unicode(enc.dumps(ret))
        print (dump)
        print os.path.join(root_path, 'src/static/js/locale/' + langs[0] + '.json')
        f = open(os.path.join(root_path, 'src/static/js/locale/' + langs[0] + '.json'), 'w')
        f.write(dump)
    except IOError, e:
        logging.error(e)
        return None

#lang = gettext.translation('exportBot', 'locale/js', ['ru'])
#print lang.__dict__
#lang.install()
#print lang.ugettext('Select service.')
#print lang.ugettext('Please authorize yourself.')

gettext_json('exportBot', 'locale/js/', langs=['en'])
gettext_json('exportBot', 'locale/js/', langs=['ru'])
